<template>
  <div id="memberPrice">
        <div>
            <el-card class="box-card">
                <el-row>
                    <el-col :span="8">
                        <el-input
                        placeholder="请输入会员卡名称"
                        v-model="memberName"
                        clearable>
                        </el-input>
                    </el-col>
                    <el-col :span="2" :offset="1"><el-button icon="el-icon-search" @click="getMemberPriceByPage" circle></el-button></el-col>
                    <el-col :span="2"><el-button type="primary" @click="addMemberPrice" round>新增</el-button></el-col>
                </el-row>
                <el-row :gutter="24" style="margin-top:20px;">
                    <el-col :span="24">
                        <el-table
                            :data="productData"
                            border
                            style="width:100%">
                            <el-table-column
                            fixed
                            prop="id"
                            label="序号"
                            >
                            </el-table-column>
                            <el-table-column
                            prop="memberName"
                            label="会员卡名称"
                            >
                            </el-table-column>
                            <el-table-column
                            prop="price"
                            label="会员卡价格"
                            >
                            </el-table-column>
                            <el-table-column
                            prop="month"
                            label="月份"
                            >
                            </el-table-column>
                            <el-table-column
                            fixed="right"
                            label="操作"
                            width="200">
                            <template slot-scope="scope">
                                <el-button @click="handleUpdate(scope.row)" type="text" size="small">编辑</el-button>
                                <el-button @click="deleteMemberPrice(scope.row)" type="text" size="small" style="color: red;">删除</el-button>
                            </template>
                            </el-table-column>
                        </el-table>
                    </el-col>
                </el-row>
                <el-row style="text-align: center;">
                    <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="currentPage4"
                    :page-sizes="[10, 20, 30, 40]"
                    :page-size="10"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="page.total">
                    </el-pagination>
                </el-row>
            </el-card>
            <!-- 数据新增弹窗 -->
            <el-dialog title="新增会员卡" :visible.sync="dialogFormVisible" @close="handleClose('productForm')">
                <el-form :model="productForm" :rules="rules" ref="productForm">
                    <el-form-item label="会员名称" :label-width="formLabelWidth" prop="memberId">
                        <el-select v-model="productForm.memberId" placeholder="请选择" >
                            <el-option
                            v-for="item in selectMemberType"
                            :key="item.id"
                            :label="item.memberName"
                            :value="item.id"
                            @click.native="choiceName(item.memberName,item.id)">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="会员月份" :label-width="formLabelWidth" prop="month">
                        <el-input v-model="productForm.month"  placeholder="请输入月份(限数字)" autocomplete="off"  oninput="value=value.replace(/[^0-9]/g,'')" ></el-input>
                    </el-form-item>
                    <el-form-item label="会员价格" :label-width="formLabelWidth" prop="price">
                        <el-input v-model.number="productForm.price"  placeholder="请输入价钱(限数字)" autocomplete="off"  oninput="value=value.replace(/[^0-9]/g,'')" ></el-input>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="dialogFormVisible = false">取 消</el-button>
                    <el-button type="primary" @click="saveMemberPrice('productForm')">确 定</el-button>
                </div>
            </el-dialog>
            <!-- 数据修改弹窗 -->
            <el-dialog title="会员卡编辑" :visible.sync="dialogFormVisibleUpdate" @close="handleClose('productFormEdit')">
                <el-form :model="productFormEdit" :rules="rules" ref="productFormEdit">
                    <el-form-item label="会员类型" :label-width="formLabelWidth" prop="memberId">
                    <el-select v-model="productFormEdit.memberId" placeholder="请选择" @input="changeMessage($event)">
                        <el-option
                            v-for="item in selectMemberType"
                            :key="item.id"
                            :label="item.memberName"
                            :value="item.id"
                            @click.native="choiceName(item.memberName,item.id)">
                        </el-option>
                    </el-select>
                    </el-form-item>
                    <el-form-item label="会员月份" :label-width="formLabelWidth" prop="month">
                        <el-input v-model="productFormEdit.month"  placeholder="请输入月份(限数字)" autocomplete="off"  oninput="value=value.replace(/[^0-9]/g,'')" @input="changeMessage($event)"></el-input>
                    </el-form-item>
                    <el-form-item label="会员价格" :label-width="formLabelWidth" prop="price">
                        <el-input v-model.number="productFormEdit.price"  placeholder="请输入价钱(限数字)" autocomplete="off"  oninput="value=value.replace(/[^0-9]/g,'')" @input="changeMessage($event)"></el-input>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="dialogFormVisibleUpdate = false">取 消</el-button>
                    <el-button type="primary" @click="updateMemberPrice('productFormEdit')">确 定</el-button>
                </div>
            </el-dialog>
        </div>
  </div>
</template>

<script>
const axios = require('axios')
export default {
  name: 'memberPrice',
  data () {
    // 校验新增修改中会员类型是否为空
    const memberId = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请选择会员类型'))
      } else {
        callback()
      }
    }
    // 校验新增修改中会员卡月份是否为空或者月份是否已录入
    const month = (rule, value, callback) => {
      this.saveValue = value - 0
      if (value === '') {
        callback(new Error('请输入会员卡月份'))
      } else if (value !== '1' && value !== '3' && value !== '12') {
        callback(new Error('只能输入1，3，12三个月份'))
      } else if (this.updatePurchaseMont === this.saveValue) {
        callback()
      } else {
        this.$axios.get('http://127.0.0.1:15000/eat-service/memberPrice/selectMemberDetailsMonth?month=' + value + '&memberId=' + this.choicememberId).then(res => {
          this.selectMonthList = res.data.obj
          if (this.selectMonthList == null) {
            callback()
            this.selectMonth = ''
          } else {
            callback(new Error('该月份已录入'))
            this.selectMonth = ''
          }
        })
      }
    }
    // 新增修改校验会员价钱不能为空不能为零
    const price = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入会员价钱'))
      } else if (value === 0) {
        callback(new Error('会员价钱不能为零'))
      } else {
        callback()
      }
    }
    return {
      // 点击编辑按钮使将获取到的月份数放进变量用于修改校验判断
      updatePurchaseMont: '',
      // 新增弹框选择卡类型是获取id放进变量用于新增校验判断
      choicememberId: '',
      // 新增修改校验存放转换值
      saveValue: '',
      // 查询会员类型结果集合
      selectMemberType: [],
      // 分页模糊查查询字段（会员卡名称）
      memberName: '',
      // 分页全查存放的数组
      productData: [],
      // 新增弹框true弹出
      dialogFormVisible: false,
      // 查看弹框true弹出
      dialogFormVisibleDatil: false,
      // 修改弹框true弹出
      dialogFormVisibleUpdate: false,
      // 新增时使用到的form对象
      productForm: {
        id: '',
        // 会员类型名称
        memberName: '',
        // 会员价格
        price: '',
        // 会员月份
        month: '',
        // 会员类型id
        memberId: ''
      },
      // 修改时使用到的form对象
      productFormEdit: {
        id: '',
        // 会员类型名称
        memberName: '',
        // 会员价格
        price: '',
        // 会员月份
        month: '',
        // 会员类型id
        memberId: ''
      },
      formLabelWidth: '120px',
      // 分页当前选中页
      currentPage4: 1,
      page: {
        pageSize: 10, // 条数
        pageNum: 1, // 页数
        total: 0
      },
      tatal: 0,
      // 新增修改校验规则
      rules: {
        memberId: [
          { validator: memberId, trigger: 'blur' }
        ],
        month: [
          { validator: month, trigger: 'blur' }
        ],
        price: [
          { validator: price, trigger: 'blur' }
        ]
      },
      // 存放查询月份校验结果
      selectMonth: ''
    }
  },
  methods: {
    // 强制更新修改会员名称输入框的值
    // 用于无法删除输入框值的时候
    changeMessage () {
      this.$forceUpdate()
    },
    // 新增修改清空值
    handleClose (formName) {
      this.$refs[formName].resetFields()// 重置数据，同时也取消了表单的校验 refundFormData：el-form用ref绑定的值，
    },
    // 分页
    handleSizeChange (ps) {
      this.page.pageSize = ps
      this.getMemberPriceByPage()
      console.log(`每页 ${ps} 条`)
    },
    handleCurrentChange (pn) {
      this.page.pageNum = pn
      this.getMemberPriceByPage()
    },
    // 新增选择赋值
    choiceName (memberName, id) {
      this.productForm.memberName = memberName
      this.choicememberId = id
    },
    // 查询会员类型
    getSelectMemberType () {
      this.$axios.get('http://127.0.0.1:15000/eat-service/memberType/getSelectMemberType').then(res => {
        this.selectMemberType = res.data.obj
      }).catch(error => {
        console.log(error)
        this.$message.error('服务器崩溃了，请稍后再尝试使用！')
      })
    },
    // 会员卡详情分页查+模糊查（会员卡名称）
    getMemberPriceByPage () {
      this.$axios.get('http://127.0.0.1:15000/eat-service/memberPrice/getMemberPriceByPage', {
        params: {
          memberName: this.memberName,
          pageSize: this.page.pageSize,
          pageNum: this.page.pageNum
        }
      })
        .then((res) => {
          this.productData = res.data.content
          this.page.total = res.data.total
        })
    },
    // 新增会员价格
    saveMemberPrice (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$axios.post('http://127.0.0.1:15000/eat-service/memberPrice/saveMemberPrice', this.productForm)
            .then(res => {
              if (res.data.obj > 0) {
                this.message('恭喜你，保存数据成功！', 'success')
                this.dialogFormVisible = false
                this.productForm = {
                  // 会员类型名称
                  memberName: '',
                  // 会员价格
                  price: '',
                  // 会员月份
                  month: '',
                  // 会员类型id
                  memberId: ''
                }
                // 重新渲染数据列表
                this.getMemberPriceByPage()
              } else {
                this.message('对不起，保存失败！', 'warning')
              }
            }).catch(error => {
              console.log(error)
              this.$message.error('服务器崩溃了，请稍后再尝试使用！')
            })
        } else {
          return false
        }
      })
    },
    // 修改会员详情
    updateMemberPrice (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          axios.put('http://127.0.0.1:8081/eat-service/memberManagement/updateMemberPrice', this.productFormEdit)
            .then(res => {
              if (res.data.code === '200') {
                this.message('恭喜你，修改数据成功！', 'success')
                this.dialogFormVisibleUpdate = false
                this.productFormEdit = {
                  // 会员类型名称
                  memberName: '',
                  // 会员价格
                  price: '',
                  // 会员月份
                  month: '',
                  // 会员类型id
                  memberId: ''
                }
                // 重新渲染数据列表
                this.getMemberPriceByPage()
              } else {
                this.message('对不起，修改失败！', 'warning')
              }
            }).catch(error => {
              console.log(error)
              this.$message.error('服务器崩溃了，请稍后再尝试使用！')
            })
        }
      })
    },
    // 删除会员卡详情
    deleteMemberPrice (row) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }// 删除提示框
      ).then(() => {
        axios.delete('http://127.0.0.1:8081/eat-service/memberManagement/deleteMemberPrice?id=' + row.id)
          .then(res => {
            if (res.data.code === '200') {
              this.message('恭喜你，删除成功！', 'success')
              this.getMemberPriceByPage()
            } else {
              this.message('删除失败', 'warning')
            }
          }).catch(error => {
            alert(error)
          })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 消息提示框
    message (message, type) {
      this.$message({
        message: message,
        type: type
      })
    },
    // 修改按钮回显值
    handleUpdate (row) {
      this.dialogFormVisibleUpdate = true
      this.productFormEdit.price = row.price
      this.productFormEdit.memberName = row.memberName
      this.productFormEdit.memberId = row.memberId
      this.productFormEdit.id = row.id
      this.productFormEdit.month = row.month
      this.choicememberId = row.memberId
      // 赋值变量
      this.updatePurchaseMont = row.month
      // 查询卡类型
      this.getSelectMemberType()
    },
    // 新增按钮弹出弹框
    addMemberPrice () {
      this.dialogFormVisible = true
      // 查询卡类型
      this.getSelectMemberType()
    }
  },
  // 初始化加载数据
  mounted () {
    // 分页全查+模糊查（会员卡名称）
    this.getMemberPriceByPage()
  }
}
</script>
<style>
</style>
